var controllerModule = angular.module("index", ['ngRoute', 'Service']);

// 自定义回车事件指令
controllerModule.directive('ngEnter', function() {
	return function(scope, element, attrs) {
		element.bind("keydown keypress", function(event) {
			if (event.which === 13) {
				scope.$apply(function() {
					scope.$eval(attrs.ngEnter);
				});

				event.preventDefault();
			}
		});
	};
});

// 配置路由
controllerModule.config(function($routeProvider) {
	$routeProvider.
			when('/projects', {
				controller: "PageController",
				templateUrl: "view/projects"
			}).
			when('/logreg', {
				controller: "PageController",
				templateUrl: 'view/logreg'
			}).
			when('/create', {
				controller: "PageController",
				templateUrl: "view/newProject"
			}).
			when('/me',{
				controller: "MeController",
				templateUrl: "view/me"
			}).
			otherwise({
				redirectTo: '/projects'
			});
});

// 页面共用控制器
controllerModule.controller("PageController", function($scope) {
	$scope.me = {
		href: "logreg"
	};
});

/* 
 * 导航栏控制器
 * 依据URL设置当前激活(active)的tab
 */
controllerModule.controller('NaviController', function($scope, $location){
	// 获取URL
	var path = $location.path();
	// 保证刷新之后仍是正确的激活状态 
	$scope.active = {
		projects: path == '/projects',
		create:	  path == '/create',
		logreg:	  path == '/logreg' || path == '/me'
	};	
	// 点击时立刻切换标签的激活状态
	$scope.switchto = {
		projects: function() {
			$scope.active = {projects: true, create: false, logreg: false};
		},
		create: function() {
			$scope.active = {projects: false, create: true, logreg: false};
		},
		logreg: function(){
			$scope.active = {projects: false, create: false, logreg: true};
		}
	};
});

/* -----------------------------
 * 注册登录控制器
 * TODO 在URL上区分登录和注册
 * TODO 在email输入时监测是否占用
 * -----------------------------*/
controllerModule.controller("LogRegController", function($scope, User, $http) {
	// 注册和登录的切换状态
	$scope.active = {
		log: false,
		reg: true
	};
	// 切换函数
	$scope.switchto = {
		log: function() {
			$scope.active = {log: true, reg: false};
		},
		reg: function() {
			$scope.active = {reg: true, log: false};
		},
	};
	// 调整label上的文字
	$scope.user = {
		email: {
			label: "电邮邮箱"
		},
		password: {
			label:"密码",
			value: ""
		},
		repassword: {
			label: "重复密码",
			value: ""
		}
	};
	// 根据状态切换submit时调用的函数
	$scope.user.submit = function() {
		($scope.active.log) ? $scope.user.log() : $scope.user.reg();
	};
    // 登录提交函数
	$scope.user.log = function() {
		console.log("hello");
		var userdata = {
			'islog': "login",
			'email': $scope.user.email.value,
			'password': $scope.user.password.value
		};
		User.log(userdata,function(data){
			if(data.success == true){
				console.log(data.userinfo);
				$scope.user.submitbtn = "登录成功";
				var obj = {href: "me"};
				$scope.me = obj;
                window.location.href = "#me";
			}else{
				$scope.user.submitbtn = "登录失败，请重试";	
			}
		});
	};
	// 注册提交函数
	$scope.user.reg = function() {
		if ($scope.user.password.value === $scope.user.repassword.value) {
			// 密码没问题
			// 取消密码不一致的提示
			document.getElementById("repassword").classList.remove("has-error");
			var userData = {
				"email"    :$scope.user.email.value,
				"name"     :$scope.user.name.value,
				"password" :$scope.user.password.value
			};
			console.log(userData);
			// 发送数据
			var res = User.reg(userData, function(res) {
				//Handle the response frome the server
				if (res.success === true) {
					//success
					document.getElementById("email-group").classList.remove("has-error");
					$scope.user.submitbtn = "注册成功";
				} else if (res.because === "email-used") {
					//email userd
					document.getElementById("email-group").classList.add("has-error");
					$scope.user.email.style += " has-error";
					$scope.user.email.label = "邮箱已被占用";
					$scope.user.email.value = "";
					document.getElementById("email").focus();
				}
			});

		} else {
			// 如果两次输入密码不一致 
			// 重置"再次输入密码框"，并将该框变红
			$scope.user.repassword.label = "两次密码不一致";
			$scope.user.repassword.input = "";
			document.getElementById("re-password").focus();
			document.getElementById("repassword").classList.add("has-error");
		}
	};
	// 监测密码框的变化
	$scope.$watch("user.password.value",function(newValue, oldValue, scope){
		if($scope.user.password.value.length < 6 && $scope.user.password.value.length > 1  ){
			$scope.user.password.label = "密码长度仍小于6位";	
		}else{
			$scope.user.password.label = "密码";	
		}
	});
	// 监测重复密码框的变化
	$scope.$watch("user.repassword.value", function(newValue, oldValue, scope){
		if($scope.user.password.value != $scope.user.repassword.value && $scope.user.repassword.value.length >2){
			$scope.user.repassword.label = "两次输入密码不一致";
		}else{
			document.getElementById("repassword").classList.remove("has-error");
			$scope.user.repassword.label = "重复密码";
		}
	});
	// 监测注册和登录状态的切换
	$scope.$watch("active.reg", function(newV,oldV,scope){
		if($scope.active.reg == true){
			$scope.user.submitbtn = "注册"
		}else{
			document.getElementById("name").removeAttribute("required");
			$scope.user.submitbtn = "登录"
		}
	});
});

/* --------------
 * 创建项目控制器
 * ------------*/
controllerModule.controller("newController", function($scope,$http) {
	$scope.new = {
		// 基本信息，第一页
		basicInfo: {
			isActive: true,
			data: {},
			save: function() {
				$scope.new.data = {
					name: $scope.new.basicInfo.name || "",
					projectInfo: $scope.new.basicInfo.intro || ""
				};
				$scope.new.data.tags = $scope.new.tag.tags || "";
				console.log($scope.new.data);
				$scope.new.teamInfo.switchTo();
			},
			switchTo: function() {
				$scope.new.basicInfo.isActive = true;
				$scope.new.teamInfo.isActive = false;
				$scope.new.richInfo.isActive = false;
			}
		},
		// 团队信息，第二页
		teamInfo: {
			isActive: false,
			member: [{name: "Andy", email: "tangpin@gmail.com"}],
			// 添加成员
			add: function() {
				$scope.new.teamInfo.member.push({
					name: $scope.new.teamInfo.name,
					email: $scope.new.teamInfo.email
				});
				$scope.new.teamInfo.name = "";
				$scope.new.teamInfo.email = "";
			},
			//保存，切换到下一步
			save: function(){
				$scope.new.data.teamInfo = {
					member: $scope.new.teamInfo.member,
					needTeamate: $scope.new.teamInfo.teamate
				};
				// 将tag信息和团队信息都序列化
				$scope.new.data.tags = JSON.stringify($scope.new.data.tags);
				$scope.new.data.teamInfo = JSON.stringify($scope.new.data.teamInfo);
				console.log($scope.new.data);		
				$http.post('project',$scope.new.data).success(function(data){
					if(data.success == true){
						console.log(data);	
						$scope.new.richInfo.switchTo();
					}
				});
			},
			switchTo: function() {
				$scope.new.teamInfo.isActive = true;
				$scope.new.richInfo.isActive = false;
				$scope.new.basicInfo.isActive = false;
			}
		},
		// 编辑更多信息，第三页
		// TODO 图片上传问题尚未解决
		richInfo: {
			isActive: false,
			switchTo: function() {
				$scope.new.richInfo.isActive = true;
				$scope.new.teamInfo.isActive = false;
				$scope.new.basicInfo.isActive = false;
			}
		},
		// 标签控制，实际上这部分在基本信息中
		tag: {
			tags: [],
			input: "",
			addTagTitle: "添加标签",
			addTag: function() {
				$scope.new.tag.tags.push($scope.new.tag.input);
				$scope.new.tag.input = "";
			},
			removeTag: function(tag) {
				var arr = $scope.new.tag.tags; 
				for(var i=0; i<arr.length; i++){
					if(arr[i] === tag){
						if(i === 0){
							arr.shift();	
						}else{
							arr.splice(i,i);
						}
					}
					console.log(arr);
				}
			},
			focus: function() {
				$scope.new.tag.addTagTitle = "输入标签并回车";
				$("#addTagInput").focus();
			},
			blur: function() {
				$scope.new.tag.addTagTitle = "添加标签";
			}
		},
		// 最终提交，由最后一个页面调用
		submit: function() {
			$scope.new.data.teamInfo = {
				member: $scope.new.teamInfo.member,
				needTeamate: $scope.new.teamInfo.teamate
			};
            $scope.new.data.tags = $scope.new.tag.tags;
			// console.log($scope.new.data);
		}
	};
	$('input[id=lefile]').change(function() {
	$('#photoCover').val($(this).val());
	});
});

/* --------------
 * 个人主页控制器
 * ------------*/
controllerModule.controller("MeController",function($scope, $http){
	$http.get('user/info').success(function(data){
		$scope.haslogin = data.haslogin;
		if(data.haslogin == true){
			$scope.userinfo = data;
		}else{
			window.location.href = "#logreg";	
		}
	});
});
/* ------------
 * 项目展示页面
 */
controllerModule.controller("ProjectController", function($scope, $http){
	$scope.project = {};
	$scope.project.cards = [
		{name:"andy"},
		{name:"pin"},
		{name:"tangpin"},
		{name:"ren"},
		{name:"wang"}
	];
});

